package com.treeliked.udpdemo.page.p2;

import com.treeliked.udpdemo.cs.UdpServer;
import com.treeliked.udpdemo.model.Message;
import lombok.Data;

import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.*;
import java.io.IOException;
import java.text.SimpleDateFormat;


/**
 * 服务器端页面
 *
 * @author lss
 * @date 2019-01-03, Thu
 */
@SuppressWarnings("Duplicates")
@Data
public class Server {


    /**
     * 屏幕宽度
     */
    private static final int SCREEN_WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;

    /**
     * 页面宽度
     */
    private static final int FRAME_WIDTH = 1300;

    /**
     * 屏幕高度
     */
    private static final int SCREEN_HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;

    /**
     * 页面高度
     */
    private static final int FRAME_HEIGHT = 803;

    public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static long RECEIVE_NUM_AMOUNT = 0;
    private static long SEND_NUM_AMOUNT = 0;

    private JPanel container;
    private JPanel infoContainer;
    private JLabel portInfoPanel;
    private JLabel receiveInfoPanel;
    private JLabel sendInfoPanel;
    private JTextArea messageArea;
    private JScrollPane messageScrollPPane;
    private JPanel messagePaneContainer;
    private JComboBox sendMsgChoser;
    private JButton sendMsgBtn;
    private JTextArea sendMsgTextArea;
    private JButton exitBtn;
    private JButton clrBtn;
    private JTextArea messageArea2;
    private JScrollPane messageScrollPane2;
    private JButton clrBtn2;


    public void addReceiveMessageAmount() {
        RECEIVE_NUM_AMOUNT++;
        EventQueue.invokeLater(() -> receiveInfoPanel.setText("已接收消息数：" + RECEIVE_NUM_AMOUNT));
    }

    public void addSendMessageAmount() {
        SEND_NUM_AMOUNT++;
        EventQueue.invokeLater(() -> sendInfoPanel.setText("已发送消息数：" + SEND_NUM_AMOUNT));

    }

    public void addReceiveMessage(Message msg) {
        EventQueue.invokeLater(() ->
                messageArea.append("ID: " + msg.getId() + "\t源端口: " + msg.getSrcPost() + "\t内容: " + msg.getContent() + "\t发送时间: " + format.format(msg.getSendTime()) + "\t类型: " + (msg.getMsgType() == Message.MESSAGE_TYPE_COMMON ? "普通" : (msg.getAckResult() == Message.ACK_RESULT_OK ? "ACK 成功" : "ACK 重发")) + "\n\n")
        );
    }

    public void addSendMessage(Message msg) {
        EventQueue.invokeLater(() ->
                messageArea2.append("ID: " + msg.getId() + "\t目的端口: " + msg.getDestPost() + "\t内容: " + msg.getContent() + "\t发送时间: " + format.format(msg.getSendTime()) + "\t类型: " + (msg.getMsgType() == Message.MESSAGE_TYPE_COMMON ? "普通" : (msg.getAckResult() == Message.ACK_RESULT_OK ? "ACK 成功" : "ACK 重发")) + "\n\n")
        );
    }

    public static void main(String[] args) throws IOException {
        JFrame frame = new JFrame("UDP 服务器 V0.0.1");


        Server server = new Server();
        UdpServer us = new UdpServer(UdpServer.DEFAULT_SERVER_PORT, server);
        server.init(us);

        us.startReceive();

        server.portInfoPanel.setText("当前端口号: " + us.getServerPort());
        server.receiveInfoPanel.setText("已接收消息：");
        server.sendInfoPanel.setText("已发送消息：");


        frame.setContentPane(server.container);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds((SCREEN_WIDTH - FRAME_WIDTH) / 2, (SCREEN_HEIGHT - FRAME_HEIGHT) / 2, FRAME_WIDTH, FRAME_HEIGHT);
        frame.setVisible(true);
    }


    @SuppressWarnings("unchecked")
    public void init(UdpServer udpServer) {

        // 显示垂直滚动条并始终保持在最下方
        messageScrollPPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        DefaultCaret caret1 = (DefaultCaret) messageArea.getCaret();
        caret1.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        messageScrollPane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        DefaultCaret caret2 = (DefaultCaret) messageArea2.getCaret();
        caret2.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        for (int i = 0; i < 10; i++) {
            sendMsgChoser.addItem(udpServer.getServerPort() + i + 1);
        }
        // 按钮事件
        exitBtn.addActionListener(e -> System.exit(0));
        clrBtn.addActionListener(e -> messageArea.setText(""));
        clrBtn2.addActionListener(e -> messageArea2.setText(""));
        sendMsgBtn.addActionListener(e -> {
            int destPort = (int) sendMsgChoser.getSelectedItem();
            String content = sendMsgTextArea.getText();
            if (content == null || content.length() == 0) {
                return;
            }
            Message msg = new Message(udpServer.getServerPort(), destPort);
            msg.setMsgType(Message.MESSAGE_TYPE_COMMON);
            msg.setContent(content);
            try {
                udpServer.sendMessage(msg);
                showAlert("发送成功");
            } catch (IOException ignored) {
                showAlert("IO异常");
            }
        });
    }

    public void showAlert(String str) {
        JOptionPane.showMessageDialog(this.container, str);
    }


}
